# -*- coding:utf-8 -*-
# !/usr/bin/env python3
# name : Alenx
#

import os, time
from datetime import datetime
# import requests

development = "Development"
enterprise = "Enterprise"
enterprisepro = "Enterprise"
appstore = "AppStore"

# AppStore sigin
appleid = "demo@demo.com"
applepassword = "demo2018"

# Enterprise CA certificate name and mobileprovision uuid
CodeSignIdentity = "iPhone Distribution: demo."
# uuid
ProvisioningProfileTest = "demotestDirProfile"
ProvisioningProfilePro = "demoProfile"

# 打包证书名称
cerName = "WheatMoney"
# 工程名称
projectName = "WheatMoney.xcworkspace"
# scheme
scheme = "WheatMoney"
# build mode
configuration = "Release"
# 时间
DATE = time.strftime('%Y-%m-%d%H%M%S')
# branch
branch = 'v1.0.5'

# 项目根目录
project_path = "/opt/demo/ios-fund"
# build path
BuildDir = "/opt/demo/build/" + scheme + "_" + DATE
# 打包后ipa存储目录
exportPath = "/Users/alenx/Desktop"
APPFILE = exportPath + "/WheatMoney.ipa"
# activePath
archivePath = BuildDir + scheme + ".xcarchive"
# export options
exportOptionsPlist = "/opt/demo/ios-fund/WheatMoney/WheatGlobalConfig.plist"

# 蒲公英Key
PGY_key = "9c86dxxxxxx841d91"
# 蒲公英APIKey
PGY_APIkey = "220fd5e840fxxxxxbbdb80e2e80"
# 蒲公英URL
PGY_URL = "https://www.pgyer.com/apiv2/app/upload"
# 版本更新描述
UpdateDescriptionTest = "Test Version"
UpdateDescriptionPro = "Production Version"


# Clean Project
def Clean_project():
    print("\033[1;35m==========>> Start clean! <<==========\033[0m")
    os.chdir(project_path)
    os.system('xcodebuild clean -configuration %s || exit ' % configuration)
    os.system('git checkout .')
    # os.system('\ngit branch --merged')
    os.system('git fetch')
    os.system('git checkout -b %s origin/%s' % (branch, branch))
    os.system('git branch -vv')
    os.system('git pull || exit\n')
    print("\n\033[1;32m==========>> Git Log <<==========\033[0m")
    os.system('git log -3 --pretty=format:"%h - %cd, %an : %s" || exit\n')
    print("\033[1;32m==========>> Clean success! <<==========\033[0m")


# Build Project
def Build_project():
    print("\033[1;35m==========>> Start archive! <<==========\033[0m")
    os.chdir(project_path)
    os.system(
        'xcodebuild archive -workspace %s -scheme %s -configuration %s -archivePath %s '
        'PROVISIONING_PROFILE_VALUE=\'Automatic\' || exit' % (projectName, scheme, configuration, archivePath))
    print("\033[1;32m==========>> Archive success! <<==========\033[0m")


# 导出ipa应用包
def ExportArchive():
    print("\033[1;35m==========>> Start export ipa! <<==========\033[0m")
    os.system("xcodebuild -exportArchive -archivePath %s -exportOptionsPlist %s -exportPath %s || exit"
              % (archivePath, exportOptionsPlist, exportPath))
    print("\033[1;32m=======>> Export ipa success! <<========\033[0m")


# 上传IPA包至蒲公英
# def UploadIpaTo(setting):
#     try:
#         print("\033[1;35m==========>> 上传ipa到蒲公英 <<==========\033[0m")
#         file = {'file': open(APPFILE, 'rb')}
#         param = {'_api_key': PGY_APIkey, 'buildUpdateDescription': setting}
#         req = requests.post(url=PGY_URL, files=file, data=param)
#         code = req.status_code
#         if code == 200:
#             print("\033[1;32m============>> 上传蒲公英成功 <<============\033[0m")
#         else:
#             print("\033[1;35m==========>> 上传蒲公英失败请手动上传 <<==========\033[0m")
#     except Exception as e:
#         exit(e)


# 根据自己项目修改
def Sed(sed):
    _devapi = "http:\/\/192.168.101:20880"  # 开发环境ip
    _testapi = "http:\/\/192.168.201:20881"  # 测试环境ip
    _proapi = "https:\/\/mobile.demo.com"  # 生产环境ip
    _testh5 = "http:\/\/192.168.201"  # 测试环境静态页面ip
    _proh5 = 'https:\/\/static.demo.com'  # 生产环境静态页面ip
    _dev = ''' sed -i '' "s/%s/%s/g" %s ''' % (_devapi, _testapi, exportOptionsPlist)
    _test = ''' sed -i '' "s/%s/%s/g" %s ''' % (_proapi, _testapi, exportOptionsPlist)
    _pro = ''' sed -i '' "s/%s/%s/g" %s ''' % (_testapi, _proapi, exportOptionsPlist)
    _prothtml = ''' sed -i '' "s/%s/%s/g" %s ''' % (_proh5, _testh5, exportOptionsPlist)
    _testhtml = ''' sed -i '' "s/%s/%s/g" %s ''' % (_testh5, _proh5, exportOptionsPlist)
    if sed == "test":
        os.system(_dev)
        os.system(_test)
        os.system(_prothtml)
    else:
        os.system(_dev)
        os.system(_pro)
        os.system(_testhtml)


def main(seting):
    # 时间
    BeginDate = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    try:
        # 清理工程
        Clean_project()
        Sed(seting)
        # 编译项目
        Build_project()
        # 导出ipa应用包
        ExportArchive()
        # # 上传APP包
        # if seting == "test":
        #     UploadIpaTo(UpdateDescriptionTest)
        #     print("\033[1;32m====> >当前环境为: %s <<====\033[0m" % UpdateDescriptionTest)
        # else:
        #     UploadIpaTo(UpdateDescriptionPro)
        #     print("\033[1;32m====>> 当前环境为: %s <<====\033[0m" % UpdateDescriptionPro)
        EndDate = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        BeginTime = datetime.strptime(BeginDate, '%Y-%m-%d %H:%M:%S')
        EndTime = datetime.strptime(EndDate, '%Y-%m-%d %H:%M:%S')
        ExportTime = (EndTime - BeginTime)
        print("\033[1;32m====>> 当前分支为: %s <<====\033[0m" % branch)
        print("\033[1;32m====>> 总用时为: %s <<====\033[0m" % ExportTime)
    except EOFError as e:
        exit(e)


if __name__ == "__main__":
    sets = input("Please input Build Setting(test,pro):")
    if sets == "test" or sets == "pro":
        main(sets)
    else:
        exit("\033[1;31m-*-*-*-*-*- 输入错误请重新输入... -*-*-*-*-*-\033[0m")
